/**
 * @module: 接口封装
 * @author: xiongsha
 * @date: 2020-05-27 14:13:42
 */

import axios from 'axios';
import { Toast } from 'antd-mobile';

// /* 被挂起的请求数组 */
let refreshSubscribers: any[] = [];
// /* push所有请求到数组中 */
function subscribeTokenRefresh(cb) {
  refreshSubscribers.push(cb);
}
function onRrefreshed() {
  refreshSubscribers.map((cb) => cb());
}

const deleteCookie = () => {
  // token 失效
  // localStorage.removeItem('token');
  // localStorage.removeItem('time');
  // request('post', '/api/v1/socials/authorizations', {
  //   code: openid ? undefined : code,
  //   openid,
  // })
  // loc
};

const ajax: any = axios.create({
  timeout: 1000 * 30,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  },
});

ajax.interceptors.request.use((config) => {
  const noToken = ['/api/v1/socials/authorizations', '/api/v1/index', '/api/v1/venues'];
  if (noToken.indexOf(config.url) !== -1) {
    // 免token的请求
    return config;
  }
  const time = Number(localStorage.getItem('time')) * 1000;
  const nowDate = new Date().valueOf();
  const token = localStorage.getItem('token');
  const openid = localStorage.getItem('openid');
  if (time <= nowDate && openid) {
    // token过期
    axios
      .put('/api/v1/authorizations/current', {
        token,
      })
      .then((res) => {
        const { access_token, expiration } = res.data.data;
        localStorage.setItem('token', access_token);
        localStorage.setItem('time', expiration);
        config.headers['Authorization'] = `${'Bearer '}${access_token}`;
        onRrefreshed();
        /* 执行onRefreshed函数后清空数组中保存的请求 */
        refreshSubscribers = [];
      })
      .catch((error) => {
        // token失效
        // if (error.response && error.response.status === 401) {
        axios
          .post('/api/v1/socials/authorizations', {
            openid,
          })
          .then((res) => {
            const { access_token, expiration, openid } = res.data.data;
            localStorage.setItem('token', access_token);
            localStorage.setItem('time', expiration);
            config.headers['Authorization'] = `${'Bearer '}${access_token}`;
            onRrefreshed();
            /* 执行onRefreshed函数后清空数组中保存的请求 */
            refreshSubscribers = [];
          });
        // }
      });
    const retry = new Promise((resolve, reject) => {
      /* (token) => {...}这个函数就是回调函数 */
      subscribeTokenRefresh(() => {
        /* 将请求挂起 */
        resolve(config);
      });
    });
    return retry;
  }
  config.headers.Authorization = `${'Bearer '}${token}`;
  return config;
});

// 添加响应拦截器
ajax.interceptors.response.use(
  (response: any) => {
    return response.data;
  },
  (error: any) => {
    // 对响应错误做点什么
    if (error.response && error.response.status === 401) {
    } else {
      Toast.fail(error.response.data.message);
      return Promise.reject(error.response.data);
    }
  },
);

const resuest = (method: string, url: string, data?: any) => {
  let sendData = data;
  if (method.toUpperCase() === 'GET') {
    sendData = {
      params: data,
    };
  }
  return ajax[method](url, sendData);
};

export default resuest;
